//游戏引擎 只有一个 做成单例模式
import { Bullets } from "./bullets";
import { myPlane } from "./myPlane";
import { Enemys } from "./enemy";
import { crashTest } from "./common";

const GameEngine = {
  enemys: [] as Array<Enemys>,
  bullets: [] as Array<Bullets>,
  testTimer: 0 as any,

  el: document.querySelector('.main') as HTMLDivElement,

  //初始化
  init(callback: Function) {
    this.el.innerHTML = '';
    this.loading(callback);
  },
  loading(callback:Function) {
    //动态创建一个div
    let logo = document.createElement('div');
    logo.className = 'logo';
    this.el.appendChild(logo);

    //显示进度条
    let loading = document.createElement('div');
    loading.className = 'loading';
    this.el.appendChild(loading);

    let loadingIndex: number = 0;

    let timer = setInterval(() => {
      loadingIndex++;
      loading.style.backgroundImage = `url(./images/loading${
        (loadingIndex % 3) + 1
      }.png)`;
      // 进度条,走了5次,清空,显示我们的战机
      if (loadingIndex > 5) {
        clearInterval(timer);
        this.el.innerHTML = '';
        callback&&callback();

        //出现我们的战机就可以 让键盘控战机
        this.keyController();
        //创建敌机
        this.createEnemy();
        //疯狂检测
        this.createTest();
      }
    }, 400);

    //背景在滚动
    let bgNum = 0;
    let bgTimer = setInterval(() => {
      bgNum += 1;
      this.el.style.backgroundPosition = `0px ${bgNum}px`;
      if (bgNum >= 853) {
        bgNum = 0;
      }
    }, 30);
  },

  //控制方向
  keyController() {
    window.addEventListener("keydown", (e: KeyboardEvent) => {
      if (e.keyCode === 37) {
        let mX = myPlane.el.offsetLeft - 10;
        if (mX <= 0) {
          mX = 0
        }

        myPlane.el.style.left = mX + 'px';
      }
      if (e.keyCode === 39) {
        let mX = myPlane.el.offsetLeft + 10;
        if (mX >= this.el.offsetWidth - myPlane.el.offsetWidth) {
          mX = this.el.offsetWidth - myPlane.el.offsetWidth
        }
        myPlane.el.style.left = mX + 'px';
      }
    })
  },
 //创建敌机
  createEnemy() {
    setInterval(() => {
      new Enemys()
    }, 2000);
  },

  //检测
  createTest() {
    this.testTimer = setInterval(() => {
      //1.敌机与子弹
      for (let eee in this.enemys) {
        for (let bbb in this.bullets) {
          let isCrash = crashTest(this.enemys[eee].el, this.bullets[bbb].el);
          if (isCrash) {
            // clearInterval(this.testTimer)
            this.enemys[eee].boom();
            this.bullets[bbb].hide();
            // break;
          }
        }
      }

      //2.敌机与战机
      for (let eee in this.enemys) {
        let isCrash = crashTest(myPlane.el, this.enemys[eee].el);
        if (isCrash) {
          //调用战机的boom,
          myPlane.boom();
          // 清空定时器
          // clearInterval(this.testTimer);
          // break;
          // 提示 游戏结束
        }
      }

    },100)
  }
};

export { GameEngine };
